package com.yuexun.concurrency;

import com.yuexun.concurrency.annoations.NotThreadSafe;
import com.yuexun.concurrency.annoations.ThreadSafe;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@ThreadSafe
public class countDown {
    //定义线程树
    public static int clientTotal = 5000;
    //允许并发的进程数
    public static int threadTotal = 200;
    //定义一个计数的值
    public static AtomicInteger count = new AtomicInteger(0);
    public static void main(String[] args)throws Exception{
        //定义一个线程池
        ExecutorService service = Executors.newCachedThreadPool();/*创建一个可缓存线程池，如果线程池长度超过处理需要，可灵活回收空闲线程，若无可回收，则新建线程*/
        //定义信号量,给出进程数
        final Semaphore semaphore = new Semaphore(threadTotal);/*Semaphore管理一系列许可证*/
        //请求完了之后得到计数总数
        final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        for(int i=0;i<clientTotal;i++){
            service.execute(()->{
                try {
                    semaphore.acquire();

                    add();
                    semaphore.release();
                }catch (Exception e){
                    log.error("excepttion",e);
                }
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();;
        service.shutdown();;
        log.info("count:{}",count.get());
    }
    private static void add(){
        count.incrementAndGet();
    }
}
